<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :inline="true" label-width="100px">
      <el-row>
        <el-form-item label="系" prop="department">
          <el-select class="select-type" v-model="form.department" clearable disabled placeholder="请选择系">
            <el-option v-for="item in evaluationDeptOptions" :key="item.deptId" :label="item.deptName"
                       :value="item.deptId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="profession">
          <el-select class="select-type" v-model="form.profession" disabled placeholder="请选择专业">
            <el-option v-for="item in evaluationProfessionOptions" :key="item.deptId" :label="item.deptName"
                       :value="item.deptId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="curriculum">
          <el-select class="select-type" v-model="form.curriculum" clearable placeholder="请选择课程" disabled>
            <el-option v-for="item in evaluationCurriculums" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="首次开设时间" prop="firstTime">
          <el-date-picker :disabled="true" size="small"
                          v-model="form.firstTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择首次开设时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="总分" prop="totalPoints">
          <el-input
            v-model="form.totalPoints"
            placeholder="请输入总分"
            clearable
            :disabled="true"
            size="small"
          />
        </el-form-item>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          v-hasRole="['expert']"
          @click="handleSelfDescription"
        >查看自评
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="exportExcel()"
        >导出
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          size="mini"-->
      <!--          v-hasRole="['expert']"-->
      <!--          @click="handleAddExpert"-->
      <!--        >查看评价-->
      <!--        </el-button>-->
      <!--      </el-col>-->
    </el-row>
    <el-dialog :title="title" :visible.sync="expertVisible" width="800px" append-to-body>
      <el-divider></el-divider>
      <el-form :model="expertForm" ref="expertForm" label-width="80px">
        <el-form-item label="专家评价" prop="expertDescription">
          <el-input
            v-model="expertForm.expertDescription"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 10}"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="selfVisible" width="800px" append-to-body>
      <el-divider></el-divider>
      <el-form :model="selfForm" ref="selfForm" label-width="80px">
        <el-form-item label="自评描述" prop="selfDescription">
          <el-input
            v-model="selfForm.selfDescription"
            type="textarea"
            :disabled="true"
            :autosize="{ minRows: 10, maxRows: 10}"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
      </div>
    </el-dialog>

    <el-table id="out-table" v-loading="loading"
              :data="applicationItemList"
              border
              max-height="710"
              :span-method="objectSpanMethod"
              :summary-method="getSummaries"
              show-summary
    >
      <el-table-column :label="this.form.curriculumName">
        <el-table-column :label='"系："+this.form.departmentName+"，专业："+this.form.professionName+"，首次开设时间："+this.form.firstTime'>
          <el-table-column label="一级指标" align="center" width="150" prop="firstItem.evaluationIndicatorDescription">
            <template slot-scope="scope">
          <span>{{
              scope.row.firstItem.evaluationIndicatorDescription + '(' + scope.row.firstItem.evaluationWeight + '分)'
            }}</span>
            </template>
          </el-table-column>
          <el-table-column label="二级指标" align="center" width="200" prop="secondItem.evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span v-html="calculationtwo(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="主要观测要素" align="center" width="300" prop="evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span v-html="calculationone(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="考核/协助部门" align="center" width="150" prop="evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span>{{ getdeptName(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="观测要素量化考核标准" align="center" width="200" prop="observation">
            <template slot-scope="scope">
          <span v-html="cutout(scope.row.observation)">
          </span>
            </template>
          </el-table-column>
          <el-table-column label="指标权重" align="center" prop="evaluationWeight">
            <template slot-scope="scope">
              <span>{{ scope.row.evaluationWeight + '%' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="自评级别" align="center" prop="selfLevel"/>
          <el-table-column label="自评分" align="center" prop="selfScore"/>
          <el-table-column label="作证材料" align="center" prop="fileName">
            <template slot-scope="scope">
              <el-link :href="`${baseUrl}${scope.row.filePath}`" :underline="false" target="_blank">
                <span class="el-icon-document" v-if="scope.row.fileName"> {{ scope.row.fileName }} </span>
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="改进措施" align="center" width="150" prop="rectify"/>
          <el-table-column v-for="(item,index) in tableHead" :key="index" :label="item.label" :property="item.property" align="center">
            <template slot-scope="scope">{{ scope.row[scope.column.property] }}</template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  getApplication,
  getItemRange
} from "@/api/business/evaluationApplication";
import math from "@/api/tool/moth";
import {listDept} from "@/api/system/dept";
import {getExpertInfo} from "@/api/business/expert";
import {listCurriculumAll} from "@/api/business/curriculum";

import FileSaver from "file-saver"
import * as XLSX from 'xlsx/xlsx.mjs';
import XLSXS from "xlsx-style"

export default {
  name: "ApplicationView",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 评估申请表格数据
      applicationItemList: [],
      evaluationIndicatorList: [],
      evaluationCurriculums: [],
      evaluationDeptOptions: [],
      evaluationProfessionOptions: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      refreshTable: true,
      // 选中数组
      applicationId: null,
      search: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      expertVisible: false,
      selfVisible: false,
      tableHead: [],
      // 专家评估描述
      selfForm: {
        selfDescription: ""
      },
      // 专家评估描述
      expertForm: {
        evaluationApplicationId: null,
        expertBy: null,
        expertDescription: ''
      },
      // 表单参数
      form: {
        evaluationApplicationId: null,
        evaluationStandardId: null,
        department: '',
        profession: '',
        curriculum: '',
        firstTime: '',
        person: null,
        description: null,
        appliedStatus: 0,
        appliedBy: null,
        auditedBy: null,
        createdAt: null,
        modifiedAt: null,
        submittedAt: null,
        auditedAt: null,
        canceledAt: null
      },
      firstItemColumn: [],
      secondItemColumn: []
    };
  },
  created() {
    if (this.$route.params && this.$route.params.applicationId) {
      this.applicationId = this.$route.params.applicationId;
    }
    this.getDepartmentList();
    this.getItemRange(this.applicationId);
    this.handleUpdate(this.applicationId);
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        evaluationApplicationId: null,
        evaluationStandardId: null,
        department: null,
        profession: null,
        curriculum: null,
        firstTime: null,
        person: null,
        description: null,
        appliedStatus: 0,
        appliedBy: null,
        auditedBy: null,
        createdAt: null,
        modifiedAt: null,
        submittedAt: null,
        auditedAt: null,
        canceledAt: null,
      };
      this.resetForm("form");
    },
    /** 查询评估申请明细列表 */
    getItemRange(applicationId) {
      this.loading = true;
      let data = {applicationId: applicationId, expertBy: 0}
      getItemRange(data).then(response => {
        if (response.data && response.data.length > 0) {
          this.applicationItemList = response.data;
          console.log("评估明细项", this.applicationItemList)
          this.applicationItemList[0].expertScoreDTOList.forEach((costInfo) => {
            //这里是根据数据循环得到的动态的表头
            this.tableHead.push({label: costInfo.expertName, property: "" + costInfo.expertBy + ""}); // 动态表头
          });
          console.log("动态表头", this.tableHead)

          //进行行合并处理
          this.getListDataForRowAndColumn(this.applicationItemList)
        }
        this.loading = false;
      });
    },
    /** 申请信息查询按钮操作 */
    handleUpdate(evaluationApplicationId) {
      this.reset();
      getApplication(evaluationApplicationId).then(response => {
        console.log("申请单查询结果", response.data)
        if (response.data) {
          this.form = response.data;
          var obj = this.evaluationDeptOptions.find((item) => item.deptId == response.data.department);
          if (obj) {
            this.departmentName = obj.deptName;
          } else {
            this.departmentName = "";
          }
          if (this.form.department) {
            this.getProfessionList(this.form.department);
            this.getCurriculumList(this.form.department);
          }
        }
      });
    },
    /** 查询自定义系字典列表 */
    getCurriculumList(department) {
      let queryDept = {department: department, enabledFlag: 0}
      listCurriculumAll(queryDept).then(response => {
        console.log("查询-课程字典", response)
        if (response.data) {
          this.evaluationCurriculums = response.data.map((item) => {
            return {
              label: item.evaluationCurriculumName,
              value: item.evaluationCurriculumId
            };
          });
        }
      });
    },
    getdeptName(row) {
      var evaluationDeptName = row.evaluationDeptName ? row.evaluationDeptName + '/' : ""
      var assistDeptName = row.assistDeptName ? row.assistDeptName : ""
      return evaluationDeptName + assistDeptName;
    },
    /**  评估明细项表格一级二级合并行操作开始 **/
    //判断需要合并行，进行数组组装
    getListDataForRowAndColumn(data) {
      let self = this;
      self.firstItemColumn = [];
      self.secondItemColumn = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          // 如果是第一条记录（即索引是0的时候），向数组中加入１
          self.firstItemColumn.push(1);
          self.pos = 0;
          self.secondItemColumn.push(1);
          self.posT = 0;
        } else {
          if (data[i].firstItem.evaluationItemId === data[i - 1].firstItem.evaluationItemId) {
            // 如果storeName相等就累加，并且push 0
            self.firstItemColumn[self.pos] += 1
            self.firstItemColumn.push(0)
            if (data[i].secondItem.evaluationItemId === data[i - 1].secondItem.evaluationItemId) {
              // 如果roomName相等就累加，并且push 0
              self.secondItemColumn[self.posT] += 1
              self.secondItemColumn.push(0)
            } else {
              self.secondItemColumn.push(1)
              self.posT = i
            }
          } else {
            // 不相等push 1
            self.firstItemColumn.push(1)
            self.pos = i;
            self.secondItemColumn.push(1)
            self.posT = i
          }
        }
      }
    },
    //行合并
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      let self = this
      if (columnIndex === 0) {
        if (self.firstItemColumn[rowIndex]) {
          let rowNum = self.firstItemColumn[rowIndex];
          return {
            rowspan: rowNum,
            colspan: rowNum > 0 ? 1 : 0
          }
        }
        return {
          rowspan: 0,
          colspan: 0
        }
      }
      if (columnIndex === 1) {
        if (self.secondItemColumn[rowIndex]) {
          let roomNum = self.secondItemColumn[rowIndex];
          return {
            rowspan: roomNum,
            colspan: roomNum > 0 ? 1 : 0
          }
        }
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    /**  评估明细项表格一级二级合并行操作结束 **/
    cutout(cellValue) {
      return cellValue.replaceAll('|', '<br/>')
    },
    calculationone(row) {
      return row.evaluationIndicatorDescription + '(' + math.multiply(row.firstItem.evaluationWeight * row.secondItem.evaluationWeight * row.evaluationWeight, 0.0001) + '分)'
    },
    calculationtwo(row) {
      return row.secondItem.evaluationIndicatorDescription + '(' + row.secondItem.evaluationWeight + '%)' + '(' + math.multiply(row.firstItem.evaluationWeight * row.secondItem.evaluationWeight, 0.01) + '分)'
    },
    // 表格合计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      console.log("列数据", columns)
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总评分';
          return;
        }
        if (column.property != "firstItem.evaluationIndicatorDescription" && column.property != "secondItem.evaluationIndicatorDescription"
          && column.property != "evaluationIndicatorDescription" && column.property != "observation"
          && column.property != "evaluationWeight" && column.property != "selfLevel" && column.property != "fileName" && column.property != "rectify") {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return math.add(prev, curr);
              } else {
                return math.add(prev, 0);
              }
            }, 0);
            sums[index] += ' 分';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },
    getDepartmentList() {
      const queryDept = {parentId: 200, status: 0}
      listDept(queryDept).then(response => {
        console.log("查询-系", response.data)
        this.evaluationDeptOptions = response.data;
      });
    },
    getProfessionList(parentId) {
      const queryDept = {parentId: parentId, status: 0}
      listDept(queryDept).then(response => {
        console.log("查询-专业", response.data)
        this.evaluationProfessionOptions = response.data;
      });
    },
    /** 自评查看 */
    handleSelfDescription() {
      console.log("自评描述", this.form.selfDescription)
      this.selfForm.selfDescription = this.form.selfDescription;
      this.selfVisible = true;
      this.title = "自评查看";
    },
    /** 专家评价弹框 */
    handleAddExpert() {
      getExpertInfo(this.applicationItemList[0].evaluationExpertId).then(response => {
        if (response.data) {
          this.expertForm = response.data;
          this.expertVisible = true;
          this.title = "专家评价查看";
        }
      });
    },

    exportExcel(excelName) {
      // 为el-table添加一个id：out-table
      // 当el-table使用了fixed时会导出两次数据，所以要先进行判断
      let fix = document.querySelector('.el-table__fixed');
      let wb;
      if (fix) {
        // 如果有fixed，先移除，然后再添加上
        wb = XLSX.utils.table_to_book(document.querySelector("#out-table").removeChild(fix))
        document.querySelector("#out-table").appendChild(fix)
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#out-table"))
      }
      // 设置列宽 字号等
      this.setExlStyle(wb['Sheets']['Sheet1']);
      let wbout = XLSXS.write(wb, {
        type: "buffer"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: "application/octet-stream"
          }),
          // 导出的文件名称
          "Data.xlsx"
        )
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    setExlStyle(data) {
      //单元格外侧框线
      const borderAll = {
        top: {
          style: 'thin',
        },
        bottom: {
          style: 'thin'
        },
        left: {
          style: 'thin'
        },
        right: {
          style: 'thin'
        }
      };
      data['!cols'] = [];
      for (let key in data) {
        if (data[key] instanceof Object) {
          // 内容不为空
          if (data[key].v !== '') {
            // 首行
            if (key[1].toString() === "1") {
              data[key].s = {
                // 边框
                // border: borderAll,
                // 居中
                alignment: {
                  horizontal: 'center', vertical: 'center'
                },
                font: {name: '微软雅黑', sz: 18, bold: true},
                // 背景色
                // fill: {bgColor: {indexed: 64}, fgColor: {rgb: "FFFF00"}}
              }
            } else if (key[1].toString() === "2") {
              data[key].s = {
                // 边框
                // border: borderAll,
                // 居中
                alignment: {
                  horizontal: 'center', vertical: 'center'
                },
                font: {name: '微软雅黑', sz: 16, bold: true}
              }
            } else if (key[1].toString() === "3") {
              data[key].s = {
                // 边框
                // border: borderAll,
                // 居中
                alignment: {
                  horizontal: 'center', vertical: 'center'
                },
                font: {name: '微软雅黑', sz: 14, bold: true}
              }
            } else {
              data[key].s = {
                // border: borderAll,
                // 自动换行
                alignment: {
                  horizontal: 'center', vertical: 'center', wrapText: 1
                },
                font: {name: '微软雅黑', sz: 11},
                numFmt: 0
              }
            }
            // 定义列宽
            if (key[1].toString() === "3") {
              let len = String(data[key].v).length
              let w = 0
              switch (String(data[key].v).length) {
                case 3:
                  w = 80;
                  break;
                case 4:
                  w = 100;
                  break;
                case 6:
                  w = 300;
                  break;
                default:
                  w = 200;
              }
              data['!cols'].push({wpx: w});
            }
          }
        }
      }
      return data;
    },
  },
};
</script>
<style lang="scss">
.tree {
  .el-tree-node {
    white-space: normal;

    .el-tree-node__content {
      height: 100%;
      align-items: start;
    }
  }
}

.el-dialog__body {
  padding: 0px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
</style>
